package com.motorhome.api.service.impl;

import com.motorhome.api.common.statics.ApiStatics;
import com.motorhome.api.dao.DeviceDao;
import com.motorhome.api.domain.DevicePositionListResult;
import com.motorhome.api.domain.DevicePositionResult;
import com.motorhome.api.domain.DevicesData;
import com.motorhome.api.domain.ResSnapshot;
import com.motorhome.api.service.DeviceApiService;
import com.motorhome.api.service.DeviceService;
import com.motorhome.base.dao.Pager;
import com.motorhome.base.util.Result;
import com.motorhome.base.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: John
 */
@Service
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    private DeviceApiService deviceApiService;

    @Autowired
    private DeviceDao deviceDao;

    @Override
    public Result getLocation(String deviceNumber) {
        if (StringUtil.isBlank(deviceNumber)) {
            return new Result(1, "deviceNumber不能为空");
        }
        DevicePositionResult devicePositionResult = deviceApiService.getDevicePosition(deviceNumber, 1);
        if (devicePositionResult != null && devicePositionResult.getResultCode() == 0) {
            return new Result(0, "成功", devicePositionResult.getResult());
        }
        return new Result(1, "设备接口异常");
    }

    @Override
    public Result getLocationOther(String deviceNumber) {
        if (StringUtil.isBlank(deviceNumber)) {
            return new Result(1, "deviceNumber不能为空");
        }
        Result devicePositionResult = deviceApiService.getDevicePositionOther(deviceNumber, 1);
//        if (devicePositionResult != null && devicePositionResult.getResultCode() == 0) {
//            return new Result(0, "成功", devicePositionResult.getResult());
//        }
//        return new Result(1, "设备接口异常");
        return devicePositionResult;
    }

    @Override
    public Result getMapLocation() {
        DevicePositionListResult devicePositionListResult = deviceApiService.getDeviceListPosition(1, 1, 500);
        if (devicePositionListResult != null && devicePositionListResult.getResultCode() == 0) {
            return new Result(0, "成功", devicePositionListResult.getResult());
        }
        return new Result(1, "设备接口异常");
    }

    @Override
    public Result setOnOff(String deviceNumber, String status) {

        DevicesData data  =  deviceDao.getDeviceData(deviceNumber);
        String ip = data.ip;
        String port = data.port;

        long i_ip = Long.parseLong(ip);
        byte[] btData = IntToByteArray(i_ip);

        ip = byteToIp(btData);
        netAddress = ip;
        PORT_NUM = Integer.parseInt(port);
        sendStr = "";

        Result ret =  UdpClient();


        return ret;
    }
    private String sendStr = "SendString";
    private String netAddress = "127.0.0.1";
    private  int PORT_NUM = 5066;

    private DatagramSocket datagramSocket;
    private DatagramPacket datagramPacket;


    public Result  UdpClient(){
        try {

            /*** 发送数据***/
            // 初始化datagramSocket,注意与前面Server端实现的差别
            datagramSocket = new DatagramSocket();
            // 使用DatagramPacket(byte buf[], int length, InetAddress address, int port)函数组装发送UDP数据报
            byte[] buf = sendStr.getBytes();
            InetAddress address = InetAddress.getByName(netAddress);
            datagramPacket = new DatagramPacket(buf, buf.length, address, PORT_NUM);
            // 发送数据
            datagramSocket.send(datagramPacket);

            /*** 接收数据***/
            byte[] receBuf = new byte[1024];
            DatagramPacket recePacket = new DatagramPacket(receBuf, receBuf.length);
            datagramSocket.receive(recePacket);

            String receStr = new String(recePacket.getData(), 0 , recePacket.getLength());
            System.out.println("Client Rece Ack:" + receStr);
            System.out.println(recePacket.getPort());

            return new Result(0, "成功");

        } catch (SocketException e) {
            e.printStackTrace();
            return new Result(1, "失败");
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return new Result(1, "失败");
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(1, "失败");
        } finally {
            // 关闭socket
            if(datagramSocket != null){
                datagramSocket.close();
            }
        }
    }

    private String  byteToIp(byte[] bt)
    {
        String str = "";
        int num=0;
        for(int i= 0;i<bt.length;i++)
        {
            num= (int) (bt[i] & 0xFF) ;
            if(i==0)
            {

                str = num +"";
            }else{
                str = str+"."+num;
            }
        }
  
        return str;
    }
    private byte[] IntToByteArray(Long n) {

        byte[] b = new byte[4];

        b[0] = (byte) (n & 0xff);

        b[1] = (byte) (n >> 8 & 0xff);

        b[2] = (byte) (n >> 16 & 0xff);

        b[3] = (byte) (n >> 24 & 0xff);

        return b;
    }

        @Override
    public Result getResList(String deviceId, String page, String pageSize) {

        if (StringUtil.isBlank(page)) {
            page = "1";
        }
        if (StringUtil.isBlank(pageSize)) {
            pageSize = "10";
        }

        Pager<ResSnapshot> pager = deviceDao.getResList(deviceId, Integer.parseInt(page), Integer.parseInt(pageSize));

        List<ResSnapshot> resSnapshotList = pager.getItems();
        List<Map<String, Object>> dataList = new ArrayList<>();
        for (ResSnapshot resSnapshot : resSnapshotList) {
            Map<String, Object> data = new HashMap<>();
            data.put("id", resSnapshot.getId());
            data.put("resname", resSnapshot.getResname());
            data.put("longitude", resSnapshot.getLongitude());
            data.put("latitude", resSnapshot.getLatitude());
            data.put("altitude", resSnapshot.getAltitude());
            data.put("termid", resSnapshot.getTermid());
            data.put("property", resSnapshot.getProperty());
            data.put("timestamp", resSnapshot.getTimestamp());

            //解析视频、图片等资源地址
            StringBuffer resUrl = new StringBuffer();
            String resName = resSnapshot.getResname();
            Long timestamp = resSnapshot.getTimestamp();
            Integer property = resSnapshot.getProperty();
            if (StringUtil.isNotBlank(resName) && timestamp != null) {
                String datePath = new SimpleDateFormat("/yyyy/MM/dd").format(new Date(timestamp * 1000));
                if (property == 1) {
                    for (int i = 1; i <= 4; i++) {
                        resUrl.append(i == 0 ? ApiStatics.DEVICE_RES_URL : "," + ApiStatics.DEVICE_RES_URL)
                                .append(datePath)
                                .append("/").append(resName).append("_").append(i).append(".jpg");
                    }
                } else if (property == 2 || property == 8) {
                    resUrl.append(ApiStatics.DEVICE_RES_URL)
                            .append(datePath)
                            .append("/").append(resName).append(".mp4");
                }
            }
            data.put("url", resUrl.toString()); //多个逗号分隔

            dataList.add(data);
        }

        return new Result(0, "成功", dataList);
    }
}
